package com.wibo.account;



import java.io.FileNotFoundException;

import weibo4android.User;
import weibo4android.Weibo;
import weibo4android.WeiboException;

import com.wibo.common.Constants;
import com.wibo.common.FileDbHelper;
import com.wibo.common.NotificationHelper;
import com.wibo.common.UserItem;
import com.wibo.common.Utility;
import com.wibo.service.IWeiboService;
import com.wibo.service.IWeiboServiceCallback;
import com.wibo.service.WeiboService;


import android.app.Activity;
import android.app.NotificationManager;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.ImageView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;

public class WiboMainTabActivity extends TabActivity implements OnClickListener {
	private TabHost mTabHost;
	private FrameLayout mTabFrame;
	private ImageView mHomeBtn;
	private ImageView mMessageBtn;
	private ImageView mDetailBtn;
	private ImageView mOtherBtn;
	private ImageView mLoadingPic;
	
	private ImageView mHomeImageView;
	private ImageView mMessageImageView;
	private ImageView mDetailImageView;
	private ImageView mOtherImageView;
	private LinearLayout mBottomBarLayout;
	
	public static final String TAG = "WiboMainTabActivity";
	
	private static Weibo mWeibo = null;
	private static OAuthConstant mAuthConstant = null;
	//private static User mUser = null;
	protected FileDbHelper mDbHelper = null;
	private static boolean mIsVerify = false;
	CUserManager mUserManager = null;
	private boolean mbRunning = false;
	
	public static final String NOTIFICATION_FRESH_COMMENTS = "com.wibo.fresh.comments";
	public static final String NOTIFICATION_FRESH_TRANSMITS = "com.wibo.fresh.transmits";
	public static final String NOTIFICATION_FRESH_FANS = "com.wibo.fresh.fans";
	
	public static final String USER_INFO = "USER_INFO";
	public static final String LOGIN_NAME = "LOGIN_NAME";
	public static final String USER_NAME = "USER_NAME";
	public static final String USER_ID = "USER_ID";
	public static final String USER_SKIN = "USER_SKIN";
	
	private static final int VERIFY_USER_FINISH = 0;
	private static final int VERIFY_USER_ERROR = 1;
	private static final int SET_MESSAGE_NEW_WEIBO = 2;
	private static final int CLEAN_MESSAGE_NEW_WEIBO = 4;
	private static final int SET_MESSAGE_NUM = 3;
	private static final int CLEAN_COMMENT_NUM = 5;
	private static final int CLEAN_TRANSMIT_NUM = 8;
	private static final int SET_FANS_NUM = 6;
	private static final int CLEAN_FANS_NUM = 7;
	
	

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if(!mbRunning){

				Log.e(TAG, "stop by not running flag!");
	    		return;
	    	}
			
			switch (msg.what) {
			case VERIFY_USER_FINISH:
				if (msg.obj != null) {
					User user = (User) msg.obj;
					mUserManager.setAccountUser(user);
					mUserManager.insertUserToDB(mDbHelper, user, Utility.USER_MYSELF);
					mUserManager.setUserId(user.getId());
					setTitle(user.getName());
					mIsVerify = true;
					
					mTabFrame.setVisibility(FrameLayout.VISIBLE);
					//ImageView iv = (ImageView) findViewById(R.id.mainLoadingImage);					
					mLoadingPic.setVisibility(ImageView.GONE);
					
//					TabWidget tabwidget = mTabHost.getTabWidget();
//					tabwidget.setVisibility(TabWidget.VISIBLE);
					mBottomBarLayout.setVisibility(LinearLayout.VISIBLE);
					//mUserManager.insertUserToDB(mDbHelper, user, Utility.USER_MYSELF);
					
					SharedPreferences settings = getSharedPreferences(USER_INFO, 0);
					Editor editor = settings.edit();
					editor.putString(USER_NAME, user.getName());
					editor.putLong(USER_ID, user.getId());
					editor.commit();
					
					Utility.mUserName = user.getName();
//
//					Intent serviceIntent = new Intent(WiboMainTabActivity.this, WeiboService.class);
//					boolean suc = getApplicationContext().bindService(serviceIntent, mAccountConnection, Context.BIND_AUTO_CREATE);
//					startService(serviceIntent);
				}
				break;
			case VERIFY_USER_ERROR:
				// 清除数据退出
				mUserManager.setAccountUser(null);
				mIsVerify = false;
				SharedPreferences settings = getSharedPreferences(WiboMainLoginActivity.SETTINGS_TOKEN_PAIR, 0);
				Editor editor = settings.edit();
				editor.putString(WiboMainLoginActivity.TOKEN, "");
				editor.putString(WiboMainLoginActivity.TOKEN_SECRET, "");
				editor.commit();
				
				Intent intent = new Intent(WiboMainTabActivity.this, WiboMainLoginActivity.class);
				startActivity(intent);
                finish();

				break;
			case SET_MESSAGE_NUM:
				mMessageImageView.setVisibility(ImageView.VISIBLE);
				if (msg.arg1 < 10 && msg.arg1 > 0) {
					mMessageImageView.setBackgroundResource(NUM_DRAWABLE[msg.arg1 - 1]);
				}else if (msg.arg1 >= 10){
					mMessageImageView.setBackgroundResource(NUM_DRAWABLE[9]);
				}
				
				break;
			case SET_MESSAGE_NEW_WEIBO:
				mUserManager.setHaveUnread(true);
				mHomeImageView.setVisibility(ImageView.VISIBLE);
				break;
			case CLEAN_MESSAGE_NEW_WEIBO:
				mUserManager.setHaveUnread(false);
				mHomeImageView.setVisibility(ImageView.INVISIBLE);
				break;
			case CLEAN_COMMENT_NUM:
				if (mUserManager.getUnreadTotalCount() >= mUserManager.getUnreadCommentCount()) {
					mUserManager.setUnreadTotalCount(mUserManager.getUnreadTotalCount() - mUserManager.getUnreadCommentCount());
					if (mUserManager.getUnreadTotalCount() > 0) {
						mMessageImageView.setVisibility(ImageView.VISIBLE);
						Drawable drawable;
						if (mUserManager.getUnreadTotalCount() < 10 && mUserManager.getUnreadTotalCount() > 0) {
							drawable = getResources().getDrawable(NUM_DRAWABLE[mUserManager.getUnreadTotalCount() - 1]);
						}else{
							drawable = getResources().getDrawable(NUM_DRAWABLE[9]);
						}
						mMessageImageView.setBackgroundDrawable(drawable);
						mUserManager.setUnreadCommentCount(0);
					}else{
						mMessageImageView.setVisibility(ImageView.INVISIBLE);
						mUserManager.setUnreadCommentCount(0);
						mUserManager.setUnreadTotalCount(0);
						mUserManager.setUnreadTransmitCount(0);
					}
				}else{
					mMessageImageView.setVisibility(ImageView.INVISIBLE);
					mUserManager.setUnreadCommentCount(0);
					mUserManager.setUnreadTotalCount(0);
					mUserManager.setUnreadTransmitCount(0);
				}
				
				break;
			case CLEAN_TRANSMIT_NUM:
				if (mUserManager.getUnreadTotalCount() >= mUserManager.getUnreadTransmitCount()) {
					mUserManager.setUnreadTotalCount(mUserManager.getUnreadTotalCount() - mUserManager.getUnreadTransmitCount());
					if (mUserManager.getUnreadTotalCount() > 0) {
						mMessageImageView.setVisibility(ImageView.VISIBLE);
						Drawable drawable;
						if (mUserManager.getUnreadTotalCount() < 10 && mUserManager.getUnreadTotalCount() > 0) {
							drawable = getResources().getDrawable(NUM_DRAWABLE[mUserManager.getUnreadTotalCount() - 1]);
						}else{
							drawable = getResources().getDrawable(NUM_DRAWABLE[9]);
						}
						mMessageImageView.setBackgroundDrawable(drawable);
						mUserManager.setUnreadTransmitCount(0);
					}else{
						mMessageImageView.setVisibility(ImageView.INVISIBLE);
						mUserManager.setUnreadCommentCount(0);
						mUserManager.setUnreadTotalCount(0);
						mUserManager.setUnreadTransmitCount(0);
					}
				}else{
					mMessageImageView.setVisibility(ImageView.INVISIBLE);
					mUserManager.setUnreadCommentCount(0);
					mUserManager.setUnreadTotalCount(0);
					mUserManager.setUnreadTransmitCount(0);
				}
				
				break;
			case CLEAN_FANS_NUM:
				mDetailImageView.setVisibility(ImageView.INVISIBLE);
				mUserManager.setUnreadFansCount(0);
				break;
			case SET_FANS_NUM:
				mDetailImageView.setVisibility(ImageView.VISIBLE);
				Drawable drawable;
				if (msg.arg1 < 10 && msg.arg1 > 0) {
					drawable = getResources().getDrawable(NUM_DRAWABLE[msg.arg1 - 1]);
					mDetailImageView.setBackgroundDrawable(drawable);
				}else if (msg.arg1 >= 10){
					drawable = getResources().getDrawable(NUM_DRAWABLE[9]);
					mDetailImageView.setBackgroundDrawable(drawable);
				}else{
					mUserManager.setUnreadFansCount(0);
					mDetailImageView.setVisibility(ImageView.INVISIBLE);
				}
				
				break;
			}
			super.handleMessage(msg);
		}
	};
	
	private static final int NUM_DRAWABLE[] = {R.drawable.btn_num_1, R.drawable.btn_num_2, R.drawable.btn_num_3, R.drawable.btn_num_4, R.drawable.btn_num_5, 
		R.drawable.btn_num_6, R.drawable.btn_num_7, R.drawable.btn_num_8, R.drawable.btn_num_9, R.drawable.btn_num_n, };

	private void sendMessage(int what, Object obj) {
		Message msg = mHandler.obtainMessage(what, obj);
		mHandler.sendMessage(msg);
	}
	
	private void sendMessage(int what, int arg1, int arg2, Object obj) {
		Message msg = mHandler.obtainMessage(what, arg1, arg2, obj);
		mHandler.sendMessage(msg);
	}
	
	private Thread mVerifyUserThread = null;
	
	private void setContentViewSkin() {
		int skin = mUserManager.getMySkin();
		switch (skin) {
		case 0:
			setContentView(R.layout.wibomaintab);
			break;
		case 1:
			setContentView(R.layout.wibomaintab_2);
			break;
		default:
			setContentView(R.layout.wibomaintab);
			break;
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mbRunning = true;
		mUserManager = CUserManager.getInstance(this);
		
		setContentViewSkin();
		
		mTabFrame = (FrameLayout) findViewById(android.R.id.tabcontent);
		
		if (mAuthConstant == null)
			mAuthConstant = OAuthConstant.getInstance();

		if (mWeibo == null)
			mWeibo = mAuthConstant.getWeibo();
		
		mWeibo.setToken(mAuthConstant.getToken(), mAuthConstant
				.getTokenSecret());
		
		if (mDbHelper == null)
			mDbHelper = new FileDbHelper(this);
		
		mTabHost = getTabHost();
		
		Intent homeIntent = new Intent(this, WiboMainActivity.class);
		homeIntent.setAction(Intent.ACTION_PICK);
        mTabHost.addTab(mTabHost.newTabSpec("home").setIndicator("首页", getResources().getDrawable(R.drawable.featureselector)).setContent(homeIntent));
        
        Intent tabIntent = new Intent(this, WiboTabActivity.class);
        tabIntent.setAction(Intent.ACTION_PICK);
        mTabHost.addTab(mTabHost.newTabSpec("tab").setIndicator("信息", getResources().getDrawable(R.drawable.ic_select_input_error)).setContent(tabIntent));
        
        Intent userIntent = new Intent(this, WiboUserDetailsActivity.class);
        tabIntent.setAction(Intent.ACTION_PICK);
        mTabHost.addTab(mTabHost.newTabSpec("user").setIndicator("我的资料", getResources().getDrawable(R.drawable.ic_select_input_error)).setContent(userIntent));
        
        Intent othersIntent = new Intent(this, WiboOthersActivity.class);
        tabIntent.setAction(Intent.ACTION_PICK);
        mTabHost.addTab(mTabHost.newTabSpec("others").setIndicator("广场", getResources().getDrawable(R.drawable.ic_select_input_error)).setContent(othersIntent));

		
		TabWidget tabwidget = mTabHost.getTabWidget();
		tabwidget.setVisibility(TabWidget.GONE);
		for (int i = 0; i < tabwidget.getChildCount(); i++) {
			TextView tv = (TextView)tabwidget.getChildAt(i).findViewById(android.R.id.title);
			tv.setVisibility(TextView.GONE);
		}
		
		mTabFrame.setVisibility(FrameLayout.GONE);
		
		mBottomBarLayout = (LinearLayout) findViewById(R.id.BottomBarLayout);
		
		mLoadingPic = (ImageView) findViewById(R.id.mainLoadingImage);
		
		SharedPreferences settings1 = getSharedPreferences(
				WiboMainActivity.USER_INFO, 0);
        String mImagePath = settings1.getString(WiboMainActivity.LOADING_IMAGE_PATH, "");

        Uri imageUri = Uri.parse(mImagePath);
        if (imageUri != null && !mImagePath.isEmpty()) {
        	try {
				if (imageUri != null) {
					ContentResolver resolver = getContentResolver();
					Bitmap bitmap = BitmapFactory.decodeFile(mImagePath);
//							.decodeStream(resolver
//									.openInputStream(imageUri));

					if (bitmap != null) {
						mLoadingPic.setImageBitmap(bitmap);
					}
				}
			} catch (/*FileNotFound*/Exception e) {
				e.printStackTrace();
			}
        }
			
		
		mHomeBtn = (ImageView) findViewById(R.id.homeBtn);
		mHomeBtn.setOnClickListener(this);
		mHomeBtn.setOnLongClickListener(new OnLongClickListener() {
			
			@Override
			public boolean onLongClick(View v) {
				Intent i = new Intent(WiboMainActivity.TO_THE_BOTTOM);
				sendBroadcast(i);
				return false;
			}
		});
		mMessageBtn = (ImageView) findViewById(R.id.messageBtn);
		mMessageBtn.setOnClickListener(this);
		mDetailBtn = (ImageView) findViewById(R.id.detailBtn);
		mDetailBtn.setOnClickListener(this);
		mOtherBtn = (ImageView) findViewById(R.id.otherBtn);
		mOtherBtn.setOnClickListener(this);
		
		mHomeImageView = (ImageView) findViewById(R.id.newWeibo);
		mMessageImageView = (ImageView) findViewById(R.id.messageNum);
		mDetailImageView = (ImageView) findViewById(R.id.fansNumView);
		
		mBottomBarLayout.setVisibility(LinearLayout.GONE);
		
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(CLEAN_HOME_ACTION);
		intentFilter.addAction(CLEAN_TRANSMITS_ACTION);
		intentFilter.addAction(CLEAN_COMMENTS_ACTION);
		intentFilter.addAction(CLEAN_FANS_ACTION);
		registerReceiver(mSetBarBroadcast, intentFilter);

		//verifyUser();
		if (!mIsVerify && Utility.isNetworkAvailable(WiboMainTabActivity.this)) {
			// 验证用户
			if (mVerifyUserThread != null) {
				if (mVerifyUserThread.isAlive()) {
					mVerifyUserThread.interrupt();
				}
				mVerifyUserThread = null;
			}
			mVerifyUserThread = new Thread(new Runnable() {
				
				@Override
				public void run() {
					try {
						User user = mWeibo.verifyCredentials();
						if (user != null) {
							sendMessage(VERIFY_USER_FINISH, user);
						}else{
							sendMessage(VERIFY_USER_ERROR, null);
						}
						
					} catch (WeiboException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						try {
							User user = mWeibo.verifyCredentials();
							if (user != null) {
								sendMessage(VERIFY_USER_FINISH, user);
							}else{
								sendMessage(VERIFY_USER_ERROR, null);
							}
							
						} catch (WeiboException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
							sendMessage(VERIFY_USER_ERROR, null);
						} catch (Exception e1) {
							e1.printStackTrace();
						}
					} catch (Exception e) {
						try {
							User user = mWeibo.verifyCredentials();
							if (user != null) {
								sendMessage(VERIFY_USER_FINISH, user);
							}else{
								sendMessage(VERIFY_USER_ERROR, null);
							}
							
						} catch (WeiboException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
							sendMessage(VERIFY_USER_ERROR, null);
						} catch (Exception e1) {
							e1.printStackTrace();
						}
						e.printStackTrace();
					}
				}
			});
			mVerifyUserThread.start();
			
		}else{
			SharedPreferences settings = getSharedPreferences(USER_INFO, 0);
			long userId = settings.getLong(USER_ID, -100);
			mUserManager.setUserId(userId);
			UserItem userItem = mUserManager.getUserFromDB(mDbHelper, mUserManager.getUserId(), Utility.USER_MYSELF);
			if (userItem != null || mUserManager.getUserId() > 0) {
				mUserManager.setUserItem(userItem);
				mUserManager.setUserId(userItem.getmUserId());
				setTitle(userItem.getmUserName());
			}else{
				finish();
			}
			mTabFrame.setVisibility(FrameLayout.VISIBLE);
			
			
			mLoadingPic.setVisibility(ImageView.GONE);
			//tabwidget.setVisibility(TabWidget.VISIBLE);
			mBottomBarLayout.setVisibility(LinearLayout.VISIBLE);

		}
		
		bindWeiboService();
		
		SharedPreferences lastPreferences = getSharedPreferences(Constants.PREFERENCE_NAME, 0);
        int lastIndex = 0;
        if (lastPreferences != null) {
        	lastIndex = lastPreferences.getInt(Constants.PREFERENCE_RECORD, 0);
		}
		mTabHost.setCurrentTab(lastIndex);
		
		
		if (mUserManager.getUnreadTotalCount() < 10 && mUserManager.getUnreadTotalCount() > 0) {
			mMessageImageView.setVisibility(ImageView.VISIBLE);
			mMessageImageView.setBackgroundResource(NUM_DRAWABLE[mUserManager.getUnreadTotalCount() - 1]);
		}else if (mUserManager.getUnreadTotalCount() >= 10){
			mMessageImageView.setVisibility(ImageView.VISIBLE);
			mMessageImageView.setBackgroundResource(NUM_DRAWABLE[9]);
		}
		
		
		if (mUserManager.getUnreadFansCount() < 10 && mUserManager.getUnreadFansCount() > 0) {
			mDetailImageView.setVisibility(ImageView.VISIBLE);
			Drawable drawable;
			drawable = getResources().getDrawable(NUM_DRAWABLE[mUserManager.getUnreadFansCount() - 1]);
			mDetailImageView.setBackgroundDrawable(drawable);
		}else if (mUserManager.getUnreadFansCount() >= 10){
			mDetailImageView.setVisibility(ImageView.VISIBLE);
			Drawable drawable;
			drawable = getResources().getDrawable(NUM_DRAWABLE[9]);
			mDetailImageView.setBackgroundDrawable(drawable);
		}
		
		if (mUserManager.getHaveUnread()){
			mHomeImageView.setVisibility(ImageView.VISIBLE);
		}
	}
	
//	private void verifyUser() {
//		if (!mIsVerify && Utility.isNetworkAvailable(WiboMainTabActivity.this)) {
//			// 验证用户
//			if (mVerifyUserThread != null) {
//				if (mVerifyUserThread.isAlive()) {
//					mVerifyUserThread.interrupt();
//				}
//				mVerifyUserThread = null;
//			}
//			mVerifyUserThread = new Thread(new Runnable() {
//				
//				@Override
//				public void run() {
//					try {
//						User user = mWeibo.verifyCredentials();
//						if (user != null) {
//							sendMessage(VERIFY_USER_FINISH, user);
//						}else{
//							sendMessage(VERIFY_USER_ERROR, null);
//						}
//						
//					} catch (WeiboException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//						try {
//							User user = mWeibo.verifyCredentials();
//							if (user != null) {
//								sendMessage(VERIFY_USER_FINISH, user);
//							}else{
//								sendMessage(VERIFY_USER_ERROR, null);
//							}
//							
//						} catch (WeiboException e1) {
//							// TODO Auto-generated catch block
//							e1.printStackTrace();
//							sendMessage(VERIFY_USER_ERROR, null);
//						} catch (Exception e1) {
//							e1.printStackTrace();
//						}
//					} catch (Exception e) {
//						try {
//							User user = mWeibo.verifyCredentials();
//							if (user != null) {
//								sendMessage(VERIFY_USER_FINISH, user);
//							}else{
//								sendMessage(VERIFY_USER_ERROR, null);
//							}
//							
//						} catch (WeiboException e1) {
//							// TODO Auto-generated catch block
//							e1.printStackTrace();
//							sendMessage(VERIFY_USER_ERROR, null);
//						} catch (Exception e1) {
//							e1.printStackTrace();
//						}
//						e.printStackTrace();
//					}
//				}
//			});
//			mVerifyUserThread.start();
//		}
//	}
	
	/* (non-Javadoc)
	 * @see android.app.TabActivity#onPostCreate(android.os.Bundle)
	 */
	@Override
	protected void onPostCreate(Bundle icicle) {
		// TODO Auto-generated method stub
		super.onPostCreate(icicle);
	}

	/* (non-Javadoc)
	 * @see android.app.ActivityGroup#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		SharedPreferences lastPreferences = getSharedPreferences(Constants.PREFERENCE_NAME, 0);
        int lastIndex = 0;
        if (lastPreferences != null) {
        	lastIndex = lastPreferences.getInt(Constants.PREFERENCE_RECORD, 0);
		}
        
        SharedPreferences settings = getSharedPreferences(USER_INFO, 0);
		long userId = settings.getLong(USER_ID, -1);
		mUserManager.setUserId(userId);
		
        //mTabHost.setCurrentTab(lastIndex);
        Bundle extras = getIntent().getExtras();
		if (extras != null) {
			int notificationId = extras.getInt("notificationId");
			int message = extras.getInt("message");
			
			if (notificationId > 0) {
				NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
				nm.cancel(notificationId);
				
				switch (message) {
				case NotificationHelper.NOTIFICATION_COMMENT:
					if (mUserManager.getUnreadCommentCount() > 0) {
						mHomeBtn.setSelected(false);
						mMessageBtn.setSelected(true);
						mDetailBtn.setSelected(false);
						mOtherBtn.setSelected(false);
						mTabHost.setCurrentTab(1);
						Intent i = new Intent(NOTIFICATION_FRESH_COMMENTS);
						sendBroadcast(i);
					}
					
					break;
				case NotificationHelper.NOTIFICATION_FANS:
					if (mUserManager.getUnreadFansCount() > 0) {
						mHomeBtn.setSelected(false);
						mMessageBtn.setSelected(false);
						mDetailBtn.setSelected(true);
						mOtherBtn.setSelected(false);
						mTabHost.setCurrentTab(2);
						Intent i = new Intent(NOTIFICATION_FRESH_FANS);
						sendBroadcast(i);
					}
					
					break;
				case NotificationHelper.NOTIFICATION_TRANSMIT:
					if (mUserManager.getUnreadTransmitCount() > 0) {
						mHomeBtn.setSelected(false);
						mMessageBtn.setSelected(true);
						mDetailBtn.setSelected(false);
						mOtherBtn.setSelected(false);
						mTabHost.setCurrentTab(1);
						Intent i = new Intent(NOTIFICATION_FRESH_TRANSMITS);
						sendBroadcast(i);
					}
					
					break;
				}
			}
			
		}else{
			mTabHost.setCurrentTab(lastIndex);
			setSelector(lastIndex);
		}

		long now = System.currentTimeMillis();
		if (now - mUserManager.getLastGetUnread() > Utility.REFRESH_INTERVAL * 1000) {
			if (mWeiboService != null) {
				try {
					settings = getSharedPreferences(WiboMainActivity.ID_PAIR, 0);
					long newestId = settings.getLong(WiboMainActivity.NEWEST_ID, -1);
					mWeiboService.getUnreadCount(newestId);
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
	}
	
	private void setSelector(int index) {
		mHomeBtn.setSelected(false);
		mMessageBtn.setSelected(false);
		mDetailBtn.setSelected(false);
		mOtherBtn.setSelected(false);
		switch (index) {
		case 0:
			mHomeBtn.setSelected(true);
			break;
		case 1:
			mMessageBtn.setSelected(true);
			break;
		case 2:
			mDetailBtn.setSelected(true);
			break;
		case 3:
			mOtherBtn.setSelected(true);
			break;
				
		}
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
	}

	private boolean bindWeiboService() {
		Intent serviceIntent = new Intent();
		serviceIntent.setAction("com.wibo.service.WeiboService");
		ComponentName name = getApplicationContext().startService(serviceIntent);
		if (name == null) {
			return false;
		}
		boolean isSuc = getApplicationContext().bindService(serviceIntent, mAccountConnection, Context.BIND_AUTO_CREATE);
		
		return isSuc;
	}
	
	private IWeiboService mWeiboService = null;
	
	private ServiceConnection mAccountConnection = new ServiceConnection() {
		
		public void onServiceDisconnected(ComponentName name) {
			mWeiboService = null;
			
		}
		
		public void onServiceConnected(ComponentName name, IBinder service) {
			mWeiboService = IWeiboService.Stub.asInterface(service);
			try{
				mWeiboService.registerCallback(mWeiboServiceCallback);
			}catch(RemoteException e){
				e.printStackTrace();
			}
			
		}
	};
	
	private IWeiboServiceCallback.Stub mWeiboServiceCallback = new IWeiboServiceCallback.Stub() {
		
		@Override
		public void unreadWeibo(long count) throws RemoteException {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void unreadTransmit(long count) throws RemoteException {
			mUserManager.setUnreadTransmitCount((int)count);
		}
		
		@Override
		public void unreadFans(long count) throws RemoteException {
			mUserManager.setUnreadFansCount((int)count);
			sendMessage(SET_FANS_NUM, (int)count, 0, null);
		}
		
		@Override
		public void unreadComment(long count) throws RemoteException {
			mUserManager.setUnreadCommentCount((int)count);
		}

		@Override
		public void haveNewWeibo(boolean isHave) throws RemoteException {
			if (isHave) {
				sendMessage(SET_MESSAGE_NEW_WEIBO, null);
			}else{
				sendMessage(CLEAN_MESSAGE_NEW_WEIBO, null);
			}
		}

		@Override
		public void unreadTotalMessages(long count) throws RemoteException {
			mUserManager.setUnreadTotalCount((int)count);
			sendMessage(SET_MESSAGE_NUM, (int)count, 0, null);
		}
	};
	
	public static final String CLEAN_HOME_ACTION = "com.wibo.account.cleanHome";
	public static final String CLEAN_COMMENTS_ACTION = "com.wibo.account.cleanComments";
	public static final String CLEAN_TRANSMITS_ACTION = "com.wibo.account.cleanTransmits";
	public static final String CLEAN_FANS_ACTION = "com.wibo.account.cleanFans";
	
	BroadcastReceiver mSetBarBroadcast = new BroadcastReceiver() {
		
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals(CLEAN_HOME_ACTION)) {
				sendMessage(CLEAN_MESSAGE_NEW_WEIBO, null);
			} else if(intent.getAction().equals(CLEAN_COMMENTS_ACTION)) {
				sendMessage(CLEAN_COMMENT_NUM, null);
			} else if(intent.getAction().equals(CLEAN_TRANSMITS_ACTION)) {
				sendMessage(CLEAN_TRANSMIT_NUM, null);
			} else if(intent.getAction().equals(CLEAN_FANS_ACTION)) {
				sendMessage(CLEAN_FANS_NUM, null);
			}
		}
	};
	/* (non-Javadoc)
	 * @see android.app.ActivityGroup#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (mVerifyUserThread != null) {
			if (mVerifyUserThread.isAlive()) {
				mVerifyUserThread.interrupt();
			}
			mVerifyUserThread = null;
		}
		try{
			unregisterReceiver(mSetBarBroadcast);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		
		if(mWeiboService != null){
			try{
				getApplicationContext().unbindService(mAccountConnection);
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				mWeiboService = null;
			}
		}
	}
	
	
	public void onTabChanged(String tabId) {
        Activity activity = getLocalActivityManager().getActivity(tabId);
        if (activity != null) {
            CharSequence title = activity.getTitle();           
            setTitle(title);
        }
 
    }

    protected void onChildTitleChanged(Activity childActivity, CharSequence title) {        
        setTitle(title);
    }

    
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.homeBtn:
			mHomeBtn.setSelected(true);
			mMessageBtn.setSelected(false);
			mDetailBtn.setSelected(false);
			mOtherBtn.setSelected(false);
			mTabHost.setCurrentTab(0);
			long now = System.currentTimeMillis();
			if (now - mUserManager.getLastGetUnread() > Utility.REFRESH_INTERVAL * 1000) {
				if (mWeiboService != null) {
					try {
						SharedPreferences settings = getSharedPreferences(WiboMainActivity.ID_PAIR, 0);
						long newestId = settings.getLong(WiboMainActivity.NEWEST_ID, -1);
						mWeiboService.getUnreadCount(newestId);
					} catch (RemoteException e) {
						e.printStackTrace();
					}
				}
			}
			break;
		case R.id.messageBtn:
			mHomeBtn.setSelected(false);
			mMessageBtn.setSelected(true);
			mDetailBtn.setSelected(false);
			mOtherBtn.setSelected(false);
			mTabHost.setCurrentTab(1);
			now = System.currentTimeMillis();
			if (now - mUserManager.getLastGetUnread() > Utility.REFRESH_INTERVAL * 1000) {
				if (mWeiboService != null) {
					try {
						SharedPreferences settings = getSharedPreferences(WiboMainActivity.ID_PAIR, 0);
						long newestId = settings.getLong(WiboMainActivity.NEWEST_ID, -1);
						mWeiboService.getUnreadCount(newestId);
					} catch (RemoteException e) {
						e.printStackTrace();
					}
				}
			}
			break;
		case R.id.detailBtn:
			mHomeBtn.setSelected(false);
			mMessageBtn.setSelected(false);
			mDetailBtn.setSelected(true);
			mOtherBtn.setSelected(false);
			mTabHost.setCurrentTab(2);
			break;
		case R.id.otherBtn:
			mHomeBtn.setSelected(false);
			mMessageBtn.setSelected(false);
			mDetailBtn.setSelected(false);
			mOtherBtn.setSelected(true);
			mTabHost.setCurrentTab(3);
			break;

		}
	}
}
